package com.archie.xunji.guanzhu.tools;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

public class HttpUtils {

	private static final int CONNECT_TIMEOUT=20000;
	private static final int READE_TIMEOUT=20000;
	private static final String USER_AGENT="ting_4.1.7("+ Build.MODEL+","+Build.VERSION.SDK_INT+")";

	public static byte[] doGet(String url) {
		byte[] ret = null;
		if (url != null) {
			HttpURLConnection conn = null;
			try {
				URL u = new URL(url);
				conn = (HttpURLConnection) u.openConnection();
				conn.setConnectTimeout(CONNECT_TIMEOUT);
				conn.setReadTimeout(READE_TIMEOUT);
				conn.setRequestMethod("GET");
				//完善HTTP请求的内容
				//设置通用的Http头信息
				//可接受的类型
//                conn.setRequestProperty("Accept", "application/*,text/*,image/*,*/*");
				//设置接受的内容压缩算法
				conn.setRequestProperty("Accept-Encoding", "gzip");
				//设置Useragent
				conn.setRequestProperty("User-Agent",USER_AGENT);

				conn.connect();
				int code = conn.getResponseCode();
				if (code == 200) {
					// TODO 给 data 赋值
					InputStream fin = null;
					try {
						fin = conn.getInputStream();
						//TODO 进行网络输入流的gzip压缩
						String encoding=conn.getHeaderField("Content-Encoding");
						if("gzip".equals(encoding)){
							fin=new GZIPInputStream(fin);
						}

						ret = StreamUtil.readStream(fin);
					} catch (IOException e) {
						e.printStackTrace();
					} finally {
						StreamUtil.close(fin);
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				StreamUtil.close(conn);
			}

		}

		return ret;
	}

	/**
	 * 判断网络是否连接
	 * @param context
	 * @return
	 */
	public static NetworkInfo getActiveNetwork(Context context)
	{
		if (context == null)
			return null;
		ConnectivityManager mConnMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (mConnMgr == null)
			return null;
		NetworkInfo aActiveInfo = mConnMgr.getActiveNetworkInfo();
		// 获取活动网络连接信息
		return aActiveInfo;
	}


	public static String sendByPost(String path,HashMap<String,String> params,String encode) throws IOException
	{		
		StringBuilder stringBuilder = new StringBuilder();
		for(Map.Entry<String, String> en:params.entrySet())
		{
			stringBuilder.append(en.getKey())
			             .append("=")
			             .append(URLEncoder.encode(en.getValue(),encode))
		                 .append("&");
		}
		

		stringBuilder.deleteCharAt(stringBuilder.length()-1);
		
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		
		conn.setRequestMethod("POST");
		conn.setConnectTimeout(5000);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		
		conn.setRequestProperty("Content-Type", " application/x-www-form-urlencoded");
		
		byte[] b = stringBuilder.toString().getBytes("utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(b.length));
		
		OutputStream outputStream = conn.getOutputStream();
		outputStream.write(b,0,b.length);
		outputStream.close();
		
		InputStream in = null;
		if(conn.getResponseCode()==200)
		{
			in = conn.getInputStream();
			return getResult(in,encode);
		}
		return null;
	}

	//��ȡ�������˵���֤���
	private static String getResult(InputStream in, String encode) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] arr = new byte[1024];
		int len = 0;
		while((len = in.read(arr))!=-1)
		{
			bos.write(arr,0,len);
		}
		byte[] b = bos.toByteArray();
		return new String(b,encode);
	}

}
